<template>
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="dialogFormVisible" width="900px" @close="close"
    :append-to-body="true">


    <div class="add-container">
      <div class="add-main">
        <div class="search-group">
          <div class="search-button">
            <el-button type="primary" icon="el-icon-plus" @click="uploadImages">上传</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="allDel">
              删除全部图片
            </el-button>

            <!-- <el-button type="primary" icon="el-icon-picture-outline" :disabled="selectRows.length > 0 ? false : true"
              @click="downloadImages">下载</el-button> -->
          </div>
        </div>
        <div class="table-list">
          <el-table v-loading="listLoading" :data="ruleForm" :element-loading-text="elementLoadingText"
            @selection-change="setSelectRows" highlight-current-row height="300" :header-cell-style="{
              'border-bottom': '1px solid #cbcccd',
              'border-top': '1px solid #cbcccd',
            }">
            <el-table-column show-overflow-tooltip type="selection"></el-table-column>
            <el-table-column show-overflow-tooltip label="序号" width="95">
              <template #default="scope">
                {{ scope.$index + listQuery.pageSize * (listQuery.pageIndex - 1) + 1 }}

              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="wenjianmc" label="图片名称"></el-table-column>
            <el-table-column show-overflow-tooltip label="图片预览">
              <template slot-scope="scope">
                <img :src="scope.row.wenjianlj" width="40px" height="40px">
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="upload_time" width="150" label="上传时间"></el-table-column>
            <el-table-column show-overflow-tooltip label="操作" min-width="50">
              <template #default="{ row }">
                <el-button type="text" @click="downloadImages(row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>


        </div>

      </div>

    </div>

    <!-- <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div> -->


    <!-- 导入文件start -->
    <el-dialog :close-on-click-modal="false" :visible.sync="importShow" destroy-on-close title="导入文件" class="m-dialog"
      :append-to-body="true">
      <upload-img api-url="wuzi/insertWuziFile" :rowid="wuziid" @success="uploadSuccess" />
    </el-dialog>

  </el-dialog>
</template>

<script>
import { doEdit } from '@/api/userManagement'
import { insertKufang, updateKufang } from '@/api/cangkujichu'
import { insertWuzi, save, updateWuzi, downloadFileByPath, chakanImage, deleteFileByPara, queryFileListByPara } from '@/api/wuzi'
import UploadImg from './uploadIMG'//上传文件
import axios from 'axios'

let _listQuery = {
  pageIndex: 1,
  pageSize: 10,
  // wuzimc: ''
}
export default {
  name: 'WarehouseManagement',
  components: { UploadImg },
  data() {
    return {
      listQuery: Object.assign({}, _listQuery),
      Wzzylist: [],
      importShow: false,
      elementLoadingText: '正在加载...',
      listLoading: false,
      selectRows: [],
      wuziid: '',
      form: {

      },
      ruleForm: [
        {
          id: 1,
          name: 'gegdg.jpg',
          time: '2010'
        },
        {
          id: 2,
          name: 'gegdg.jpg',
          time: '2010'
        }
      ],
      rules: {
        yiyongkr: [
          { required: true, trigger: 'blur', message: '请输入已用库容' },
        ],
        ///  password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        /// email: [{ required: true, trigger: 'blur', message: '请输入邮箱' }],
        // permissions: [
        //  { required: true, trigger: 'blur', message: '请选择权限' },
        // ],
      },
      title: '',
      dialogFormVisible: false,


    }
  },
  async mounted() {
    //物资分类
    this.Wzzylist = await this.$util.getWzzy()

  },
  created() { },
  methods: {
    setSelectRows(val) {
      this.selectRows = []
      val.forEach((i) => {
        this.selectRows.push(i.id)
      })

    },
    uploadSuccess() {
      this.importShow = false
      this.fetchData()
    },
    uploadImages() {

      this.importShow = true
    },
    downloadImages(row) {
      // if (this.selectRows.length == 0) {
      //   this.$message({
      //     message: '请先勾选数据，再进行下载操作',
      //     type: 'warning',
      //   });
      //   return
      // } else if (this.selectRows.length > 1) {
      //   this.$message({
      //     message: '目前支持图片单一下载',
      //     type: 'warning',
      //   });
      //   return
      // }
      // this.$confirm('确认下载选中的数据吗？', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(async () => {
      //   let data = {
      //     id: this.selectRows[0],
      //   }
      //   this.postDownload('/wuzi/downloadFileByPath', data, 'wuzi')
      // })
      let data = {
        id: row.id,
      }
      this.postDownload('/wuzi/downloadFileByPath', data, 'wuzi')
    },
    async showEdit(row) {
      this.title = '物资图片'
      this.wuziid = row[0].id
      this.fetchData();
      this.dialogFormVisible = true
    },
    async fetchData() {
      const wzData = await queryFileListByPara({ wuziid: this.wuziid })
      this.ruleForm = wzData.data
    },


    allDel() {
      let str = this.selectRows.join(',')
      // if (str === '') {
      //   this.$message({
      //     message: '请先勾选数据，再进行一键删除操作',
      //     type: 'warning',
      //   });
      //   return
      // }
      this.$confirm('确认删除全部图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        let data = {
          wuziid: this.wuziid,
        }
        data.idsList = []
        data.idsList.push('111')
        const res = await deleteFileByPara(data)

        this.fetchData()
        this.$message({
          message: res.msg,
          type: 'success',
        })

      })
    },

    close() {
      this.dialogFormVisible = false
    },
    save() {
      this.close()
    },
    postDownload(url, data, fileName) {
      return axios({
        // 用axios发送post请求
        url: 'http://localhost:8081' + url, // 请求地址
        data, // 参数
        method: 'post',
        responseType: 'blob',
        headers: {
          'Content-Type': 'multipart/form-data',
          token: localStorage.getItem('token'),
        },
      })
        .then((res) => {
          // console.log(res);
          // 处理返回的文件流
          // 获取http头部的文件名信息，若无需重命名文件，将下面这行删去
          // if (!fileName) fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1])

          /* 兼容ie内核，360浏览器的兼容模式 */
          const blob = new Blob([res.data], { type: res.data.type })
          /* 兼容ie内核，360浏览器的兼容模式 */
          if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, fileName)
          } else {
            /* 火狐谷歌的文件下载方式 */
            let url1 = window.URL.createObjectURL(blob)
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url1

            link.setAttribute('download', fileName + ".png")
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
          }
          this.$message({
            message: '下载成功',
            type: 'success',
          })
          // console.log(res);
          return Promise.resolve(res.data)
        })
        .catch((err) => {
          this.$message({
            message: err,
            type: 'error',
          })
          return Promise.resolve(err)
        })
    }
  },
}
</script>
<style lang="scss" scoped>
.el-select--small {
  width: 100%;
}

.search-button {
  margin-left: auto;
  padding: 10px 20px;

  .el-button {
    font-size: .14rem !important;
  }
}
</style>